<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      .container {
        width: 520px;
        height: 280px;
        position: relative;
        overflow: hidden;
        /* margin: 0 auto; */
      }
      .imgContainer {
        width: 520px;
        height: 280px;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="imgContainer">
        <img src="./images/下载.png" />
        <img src="./images/下载 (1).png" />
        <img src="./images/下载 (2).png" />
        <img src="./images/下载 (3).png" />
        <img src="./images/下载 (4).png" />
      </div>
    </div>

    <button>点击下一张</button>
    <script>
      var buttonEle = document.querySelector("button");
      var containerEle = document.querySelector(".container");
      var imgContainerEle = document.querySelector(".imgContainer");

      var page = 1;
      function autoPlay() {
        var timer = setInterval(function () {
          move(imgContainerEle, -280 * page, "top", function () {
            console.log("运动完成");
            page++;
            if (page == 5) {
              page = 1;
              imgContainerEle.style.top = "0px";
            }
          });
        }, 2000);
        buttonEle.onmouseenter = function () {
          //   console.log("停止");
          clearInterval(timer);
        };
        buttonEle.onmouseleave = function () {
          autoPlay();
        };
      }
      //   点击按钮
      buttonEle.onclick = function () {
        move(imgContainerEle, -280 * page, "top", function () {
          // console.log("运动完成");
          page++;
          if (page == 5) {
            page = 1;
            imgContainerEle.style.top = "0px";
          }
        });
      };

      autoPlay();

      function move(ele, target, dir, cb) {
        function fn() {
          var num = parseInt(getComputedStyle(ele)[dir]);
          var speed = target < num ? -10 : 10;
          if (num == target) {
            // console.log("停止了");
            cb && cb();
          } else {
            num += speed;
            ele.style[dir] = num + "px";
            requestAnimationFrame(fn);
          }
        }
        fn();
      }
    </script>
  </body>
</html>
